package com.xssq.mvc.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.xssq.mvc.Config;
import com.xssq.mvc.HttpContext;
import com.xssq.mvc.ViewResolver;

public class DefaultViewResolver implements ViewResolver {
	
	@Override
	public void resolve(Object view) throws IOException {
		HttpContext.getResponse().setCharacterEncoding("UTF-8");
		// 如果是ajax请求就返回json
		if (this.isAjax()) {
			Map<String, Object> data = new HashMap<>();
			Enumeration<String> names = HttpContext.getRequest().getAttributeNames();
			while (names.hasMoreElements()) {
				String name = names.nextElement();
				data.put(name, HttpContext.getRequest().getAttribute(name));
			}
			this.responseJson(data);
		} else if (view instanceof String) {
			String result = view.toString();
			// 重定向
			if (result.startsWith("redirect:")) {
				this.redirect(result.substring(9));
				return;
			}
			// 请求转发
			String path = Config.DEFAULT_JSP_PATH + result + ".jsp";
			this.forward(path);
		} else {
			// 不返回任何内容
			HttpContext.getResponse().sendError(HttpServletResponse.SC_NO_CONTENT);
		}
	}
	
	/**
	 * 判断是否为ajax请求
	 * @return
	 */
	private boolean isAjax() {
		if (null != HttpContext.getRequest().getHeader("X-Requested-With")) {
			return true;
		}
		return false;
	}
	
	/**
	 * 重定向
	 */
	private void redirect(String path) {
		try {
			HttpContext.getResponse().sendRedirect(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 请求转发
	 * @param path
	 */
	private void forward(String path) {
		try {
			HttpContext.getRequest().getRequestDispatcher(path).forward(HttpContext.getRequest(), HttpContext.getResponse());
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 响应json
	 * @param object
	 */
	private void responseJson(Object object) {
		HttpServletResponse response = HttpContext.getResponse();
		response.setContentType("application/json");
		try {
			PrintWriter writer = response.getWriter();
			writer.write(new Gson().toJson(object));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
